//
//  ClubHomeViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/26.
//

import UIKit
import JXSegmentedView
import SnapKit
import SwiftEntryKit
import swiftScan

class ClubHomeViewController: ClubBaseViewController, RaeLottieAnimationProtocol, RaeAnimationProtocol {

    private var messageButton = c_make_ex(UIButton.self)
        .image("Home_msg").image("Home_msgSel", state: .selected).end()
    private let scanButton = c_make_ex(UIButton.self)
        .image("Home_scan").end()
    private let searchButton = c_make_ex(UIButton.self)
        .image("Home_search").end()
    private lazy var bellPreView: RaeLottieAnimationView = {
        animation.make(.bellAnimation, loopMode: .loop)
    }()
    private var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect.zero)
    private var segmentedDataSource: JXSegmentedTitleDataSource!
    private var listContainerView: JXSegmentedListContainerView!
    private var emptyView = ClubHomeEmptyDataView()
    var titles:[String] = Array()
    var tagModel: ClubHomeConfigModel = ClubHomeConfigModel()
    private var scanVC = ClubScanViewController()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            loadMessageInfo(user_id: uid)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        loadUpdateInfo()
        getHomeAlert()
        
        view.subviews{
            messageButton
            scanButton
            searchButton
            segmentedView
            bellPreView
        }
        
        searchButton.addTarget(self, action: #selector(searchButtonClick), for: .touchUpInside)
        scanButton.addTarget(self, action: #selector(scanButtonClick), for: .touchUpInside)
        messageButton.addTarget(self, action: #selector(messageButtonClick), for: .touchUpInside)
        
        segmentedDataSource = JXSegmentedTitleDataSource()
        segmentedDataSource.titles = []
        
        segmentedDataSource.isTitleColorGradientEnabled = true
        segmentedDataSource.titleNormalColor = "#47494D".toColor
        segmentedDataSource.titleSelectedColor = "#17181A".toColor
        segmentedDataSource.titleNormalFont = 15.font_semiBold!
        segmentedDataSource.titleSelectedFont = 17.font_semiBold!
        segmentedDataSource.itemSpacing = 11.0.Scale
        segmentedDataSource.isItemSpacingAverageEnabled = false
        segmentedView.dataSource = segmentedDataSource
        
        let indicator = JXSegmentedIndicatorImageView()
        indicator.image = "Home_tag".toImage
        indicator.indicatorWidth = 13.0.Scale
        indicator.indicatorHeight = 13.0.Scale
        segmentedView.indicators = [indicator]
        
        segmentedView.delegate = self
        segmentedView.backgroundColor = .clear   
        
        listContainerView = JXSegmentedListContainerView(dataSource: self)
        view.addSubview(listContainerView)
        
        segmentedView.listContainer = listContainerView
        
        segmentedView.leading(0).top(CGFloat.statusHeight).height(44.0.Scale).trailing(105)
        messageButton.trailing(12.0.Scale).size(24.0.Scale)
        messageButton.CenterY == segmentedView.CenterY
        bellPreView.trailing(12.0.Scale).size(24.0.Scale)
        bellPreView.CenterY == segmentedView.CenterY
        scanButton.trailing(44.0.Scale).size(24.0.Scale)
        scanButton.CenterY == segmentedView.CenterY
        searchButton.trailing(76.0.Scale).size(24.0.Scale)
        searchButton.CenterY == segmentedView.CenterY
        
        bellPreView.isHidden = true
        let messageTap = UITapGestureRecognizer(target: self, action: #selector(clickMessageTap))
        bellPreView.isUserInteractionEnabled = true
        bellPreView.addGestureRecognizer(messageTap)
        
        listContainerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(segmentedView.snp.bottom)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        emptyView.frame = CGRect(x: 0, y: CGFloat.navi_height + 150, width: .screenWidth, height: 250.0.Scale)
        emptyView.isHidden = true
        view.addSubview(emptyView)
        emptyView.reloadBlock = {
            self.loadData()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(toRankListVC), name: .toAllRankListVC, object: nil)
    }
}

//MARK: Data
extension ClubHomeViewController {
    
    private func loadData(){
        
        Task{
            let models = await network.request(.homeConfig,type: ClubHomeConfigModel.self,isShowError: false)
            if models.isSuccess, let model = models.model {
                self.emptyView.isHidden = true
                for mod in model.index_top {
                    if mod.status == true {
                        self.titles.append(mod.name)
                        self.tagModel.index_top.append(mod)
                    }
                }
                self.segmentedDataSource.titles = self.titles
                self.segmentedView.reloadData()
            }else{
                self.emptyView.isHidden = false
            }
        }
    }
    
    ///查看是否有新消息
    func loadMessageInfo(user_id: String) {
        
        Task{
            let models = await network.request(.newMessage,isShowError: false)
            if models.isSuccess {
                self.messageButton.isHidden = true
                self.bellPreView.isHidden = false
            }else{
                self.messageButton.isHidden = false
                self.bellPreView.isHidden = true
            }
        }
        Task {
            let res = await network.request(.mineInfo(uid: user_id),type: ClubMineModel.self,isShowError: false)
            if res.isSuccess, let model = res.model {
                ClubUser = model.user
            }
        }
    }
    
    func getHomeAlert() -> Void {
        
        Task{
            let models = await network.request(.homeAlert,type: ClubHomeAlertModel.self,isShowError: false)
            if models.isSuccess, let model = models.model {
                if model.status {
                    let alertView = ClubHomeAlertView()
                    alertView.model = model
                    alertView.toGameDetailBlock = { gameId in
                        let detailVC = ClubGameDetailViewController()
                        detailVC.gameId = gameId
                        self.navigationController?.pushViewController(detailVC, animated: true)
                    }
                    self.entryAnimate.animation(show: alertView)
                }
            }
        }
    }
    
    //版本更新
    private func loadUpdateInfo(){
        let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
        Task{
            // 去除小数点
            let noDotString = version?.replacingOccurrences(of: ".", with: "")
            let models = await network.request(.appUpdate(codeVersion: noDotString ?? ""),type: ClubAppUpdateModel.self,isShowError: false)
            if models.isSuccess, let model = models.model {
                if model.update {
                    let versionV = ClubVersionView(frame: UIScreen.main.bounds)
                    versionV.model = model
                    UIApplication.window?.addSubview(versionV)
                }
            }
        }
    }
    
    @objc private func toRankListVC(){
        ClubGlobalTool.shared.newGameList = true
        self.segmentedView.selectItemAt(index: 1)
    }
}

//MARK: JXSegmentedListContainerViewDataSource
extension ClubHomeViewController:JXSegmentedListContainerViewDataSource,JXSegmentedViewDelegate {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return segmentedDataSource.dataSource.count
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        
        let type = self.tagModel.index_top[index].type
        if type == "1" {
            return ClubHomeRecommendViewController()
        }else if type == "5" {
            return ClubRankListViewController()
        }else if type == "2" {
            return ClubFindGameViewController()
        }else if type == "11" {
            
            let wukongVC = ClubWuKongViewController()
            wukongVC.gid = self.tagModel.index_top[index].gid
            return wukongVC
        }
        return ClubRankListViewController()
    }
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        
    }
}

//MARK: action
extension ClubHomeViewController {
    
    @objc func searchButtonClick() -> Void {
        
        self.navigationController?.pushViewController(ClubGamesSearchViewController(), animated: true)
    }
    
    @objc func messageButtonClick() {
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            self.navigationController?.pushViewController(ClubMessageViewController(), animated: true)
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    @objc private func scanButtonClick(){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            //设置扫码区域参数
            var style = LBXScanViewStyle()
            style.centerUpOffset = 44
            style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner
            style.photoframeLineW = 2
            style.photoframeAngleW = 18
            style.photoframeAngleH = 18
            style.isNeedShowRetangle = false

            style.anmiationStyle = LBXScanViewAnimationStyle.LineMove

            style.colorAngle = UIColor(red: 0.0/255, green: 200.0/255.0, blue: 20.0/255.0, alpha: 1.0)

            style.animationImage = UIImage(named: "qrcode_Scan_weixin_Line")

//            let vc = ClubScanViewController()
            scanVC.scanStyle = style
            scanVC.readyString = "加载中"
            scanVC.scanResultDelegate = self
            let v = UIView()
            v.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
            v.backgroundColor = .clear
            self.present(scanVC, animated: true)
            scanVC.qRScanView?.addSubview(v)
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    @objc private func clickMessageTap(){
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            self.navigationController?.pushViewController(ClubMessageViewController(), animated: true)
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
}

extension ClubHomeViewController: LBXScanViewControllerDelegate {
    func scanFinished(scanResult: LBXScanResult, error: String?) {
        
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(400)) {
            if scanResult.strScanned?.hasPrefix("LoginToken") == true {
                self.scanVC.dismiss(animated: true) {
                    let vc = ClubScanLoginViewController()
                    vc.strScanned = scanResult.strScanned ?? ""
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                
            } else if scanResult.strScanned?.hasPrefix("http") == true{
                let url = URL(string: scanResult.strScanned ?? "")
                if url != nil {
                    UIApplication.shared.open(url!)
                } else {
                    "二维码无效".toast_error
                }
            } else {
                "二维码无效".toast_error
            }
        }
    }
    
}
